 $(function(){
      $("#header").load("header.html");
      laydate.render({
         elem:'#tar_begin',
         max:0,
         done:function(value,date){
             console.log(value);
         }
      });
      laydate.render({
         elem:'#tar_end',
         max:1,
         done:function(value,date){
             console.log(value);
         }
      });
      $(document.body).css({
        "overflow-x":"hidden"
        });
     var domain='lv';
     //获取cookie中的domain用于多站点
//      var domain=$.cookie('domain');
//      console.log(domain);
      //获取cookie中的iaAdmin用于判断是否显示权限设置按钮
//      var isAdmin=$.cookie('isAdmin');
//     if(isAdmin==0||typeof(isAdmin)=='undefined')
//         $(".setPer").hide();
      listDomArr = [],
      currIndex = 0,
      currTimes="0",
      miniRefreshArr = [];
      var windowWidth=$(document.body).width();
      var bindEvent=Tool.bindEvent;
      var addToken=Tool.addTokenToParams;
      var chartview0 = echarts.init(document.getElementById('chart0'));
      var chartview1 = echarts.init(document.getElementById('chart1'));
      var chartview2 = echarts.init(document.getElementById('chart2'));
      var chartview3 = echarts.init(document.getElementById('chart3'));
      var chartview4 = echarts.init(document.getElementById('chart4'));
      var dz_obj={今天:'0',昨天:'-1',最近7天:'-7',最近30天:'-30'};
      //时间选择器
      $("#pt_select").val('今天');
      $("#pt_select").bind("change",function(){
          currTimes=dz_obj[$(this).val()];
          var times=currTimes,index=currIndex,type=String(parseInt(index)+1);
          listDomArr[index] = '#chart' + index;
          var jparms={type:type,times:times,chart:listDomArr[index],index:index};
          requestform(jparms);

      });
      //时间筛选
      $("#timesend").click(function(){
         var beginDate=$("#tar_begin").val();
         var endDate=$("#tar_end").val();
         if(beginDate==null||beginDate.trim().length==0){
             alert("筛选开始时间不能为空");
             return;
         }
         if(endDate==null||endDate.trim().length==0){
             alert("筛选结束时间不能为空");
             return;
         }
        var timeRange=beginDate+"/"+endDate;
        var times=timeRange,index=currIndex,type=String(parseInt(index)+1);
        listDomArr[index] = '#chart' + index;
        var jparms={type:type,times:times,chart:listDomArr[index],index:index};
        requestform(jparms);

      });
      var requestform =function(rs_data){
          if(typeof(domain)!='undefined'){
              rs_data.domain=domain; //添加当前的网站域名 用以读取不同站点的数据
          }
          var chartIndex=rs_data.type;
          var chartTitle='流量统计',chartPlot='line',chartId=rs_data.chart;
          if(chartIndex=='2'){
              chartTitle='流量来源';
              chartPlot='bar';
          }
          else if(chartIndex=='3'){
               chartTitle='流量分布';
                chartPlot='line';
          }else if(chartIndex=='4'){
              chartTitle='订单统计';
              chartPlot='line';
          }else if(chartIndex=='5'){
              chartTitle='各国网速';
              chartPlot='line';
          }
          var jobj={cahrtId:chartId,chartTitle:chartTitle,chartPlot:chartPlot,index:rs_data.index};
          $.ajax({
                url:doGetAnalyticsData,
                type:"POST",
                data:JSON.stringify(addToken(rs_data)),
                contentType:"application/json;charset=UTF-8",
    		    xhrFields: {
    		    withCredentials: false
    		          },
    		    crossDomain: true,
                beforeSend:function(xhr){
                    showLoading();
                    //发送请求前运行的函数
                },
                success:function(result){
                    hideLoading();
                   console.log(result);
                    var data=result.data;
                    var datalist=data.datalist;
                    var columnlist=data.columnsList;
                    var total=data.total;
                    var xdata=new Array();
                    var ydata=new Array();

                    for(var i=0;i<datalist.length;i++){
                        //xdata
                        if(chartIndex=='5'){
                            continue;
                        }else{
                            xdata.push(datalist[i][0]);
                        }
                        //ydata
                        if(chartIndex=='4'){
                            ydata.push(datalist[i][2]);
                        }else if(chartIndex=='5'){
                               continue;
                        }else if(chartIndex=='1'){
                            ydata.push(datalist[i][4]);
                        }else{
                            ydata.push(datalist[i][3]);
                        }
                    }
                    if(chartIndex=='5'){
                        xdata=datalist[0]['xAxis'];
                        for(var i=0;i<datalist.length;i++){
                            ydata.push(datalist[i]['yAxis']);
                        }
                    }

                    if(jobj.index==3){
                       fillContents(total,rs_data,datalist,jobj);
                    }else{
                        fillContents(total,rs_data,datalist,jobj);
                        drawCharts(xdata,ydata,jobj);
                    }


                },
                error:function(xhr,status,error){
                    hideLoading();
                    alert(status.toString()+'链接错误或超时!')
                }
            });
      };
      function fillContents(data,rs_data,detail,info){
          var index=rs_data.index;
          var req_type=rs_data.type;
          var req_time=rs_data.times;
          if(index==0){
              var sessions=data['ga:sessions'];
              var pageviews=data['ga:pageviews'];
              var hits=data['ga:hits'];
              $("#pv_val").text(sessions);
              $("#pp_val").text(pageviews);
              $("#ip_val").text(hits);
              $("#pv_rate").text('人均浏览:'+(parseInt(pageviews)/parseInt(sessions)).toFixed(2));
              $("#hit_rate").text('人均点击:'+(parseInt(hits)/parseInt(sessions)).toFixed(2));
              $("#uv_val").text(data['ga:users']);
              $("#scan_tb").children().each(function(){
                       $(this).remove();
                    });

              var html = '';
              $.each(detail, function (key, value) {
                    html += '<tr>'+
                    '<td>'+value[0]+'</td>' +
                    '<td>'+value[3]+'</td>' +
                    '<td>'+value[4]+'</td>' +
                    '<td>'+value[5]+'</td>' +
                    '<td>'+value[1]+'</td>' +
                    '</tr>';
                });
              $("#scan_tb").append(html);

          }else if(index==1){
              $("#plat_tb").children().each(function(){
                       $(this).remove();
                    });

              var html = '';
              $.each(detail, function (key, value) {
                    html += '<tr>'+
                    '<td>'+value[0]+'</td>' +
                    '<td>'+value[3]+'</td>' +
                    '<td>'+'1'+'</td>' +
                    '<td>'+value[2]+'</td>' +
                    '<td>'+value[1]+'</td>' +
                    '</tr>';
                });
              $("#plat_tb").append(html);

          }else if(index==2){
              $("#country_tb").children().each(function(){
                       $(this).remove();
                    });

              var html = '';
              $.each(detail, function (key, value) {
                    html += '<tr>'+
                    '<td>'+value[0]+'</td>' +
                    '<td>'+value[3]+'</td>' +
                    '<td>'+'1'+'</td>' +
                    '<td>'+value[2]+'</td>' +
                    '<td>'+value[1]+'</td>' +
                    '</tr>';
                });
              $("#country_tb").append(html);
          }
          else if(index==3){
              //此处再进行magentoAPI的请求
            var req_data={times:req_time,type:req_type};
            $.ajax({
                url:doGetMagento,
                type:"POST",
                data:JSON.stringify(req_data),
                contentType:"application/json;charset=UTF-8",
    		    xhrFields: {
    		          withCredentials: false
    		      },
    		    crossDomain: true,
                beforeSend:function(xhr){
                    $("#xsje").text('请求中...');
                    $("#ddsl").text('请求中...');
                    $("#dfhs").text('请求中...');
                    $("#zsps").text('请求中...');
                    $("#dzfje").text('请求中...');
                    $("#dzfbs").text('请求中...');
                    $("#zhl").text('请求中...');
                    $("#xyh").text('请求中...');
                    $("#kdj").text('请求中...');
                    showLoading();
                    //发送请求前运行的函数
                },
                success:function(result){
                    hideLoading();
                    console.log(result);
                    var data=result.data;
                    var totalRev=parseFloat(data['totalRevenue']);
                    var haveRev=parseFloat(data['revenueMoney']);
                    var totalOrds=parseInt(data['totalOrder']);
                    var conversionRate=data['conversionRate'];
                    var newCustomerPercent=data['newCustomerPercent'];
                    var perCustomerRev=data['perCustomerRev'];
                    var haveDoneOrds=parseInt(data['completeOrders'])+parseInt(data['processOrders'])+parseInt(data['deliveryOrders']);
                    $("#xsje").text(totalRev+'$');
                    $("#ddsl").text(totalOrds+'笔');
                    $("#dfhs").text(data['processOrders']+'笔');
                    $("#zsps").text(data['totalProducts']+'个');
                    $("#dzfje").text('待支付:'+(totalRev-haveRev).toFixed(2)+'$');
                    $("#dzfbs").text('待支付:'+String(totalOrds-haveDoneOrds)+'笔');
                    $("#zhl").text(conversionRate);
                    $("#xyh").text(newCustomerPercent);
                    $("#kdj").text(perCustomerRev+'$');
                    //国家列表数据展示
                    var countryOrder=data['countryOrder'];
                    var countryRevenue=data['countryRevenue'];
                    var countrys=[];
                    for(var country in countryOrder){
                        if(countryOrder.hasOwnProperty(country))
                            countrys.push(country);
                    }
                    $("#order_tb").children().each(function(){
                       $(this).remove();
                    });
                    var html = '';
                    $.each(countrys, function (key, value) {
                        var c_rev=countryRevenue[value];
                        var c_tra=countryOrder[value];
                        html += '<tr>'+
                        '<td>'+value+'</td>' +
                        '<td>'+c_rev+'</td>' +
                        '<td>'+c_tra+'</td>' +
                        '<td>'+(parseFloat(c_rev)/parseInt(c_tra)).toFixed(2)+'</td>' +
                        '</tr>';
                    });
                     $("#order_tb").append(html);
                     //draw chart
                    var xValue=data['xAxis'];
                    var yValue=data['yAxis'];
                    drawCharts(xValue,yValue,info);

                },
                error:function(xhr,status,error){
                    hideLoading();
                    alert(status.toString()+'链接错误或超时!')
                    }
                });


          }else{
               $("#speed_tb").children().each(function(){
                       $(this).remove();
                    });

              var html = '';
              $.each(detail, function (key, value) {
                    html += '<tr>'+
                    '<td>'+value['name']+'</td>' +
                    '<td>'+parseFloat(value['avgSpeed']).toFixed(2)+'</td>' +
                    '<td>'+parseFloat(value['avgDownload']).toFixed(2)+'</td>' +
                    '</tr>';
                });
              $("#speed_tb").append(html);
          }
      }

      var initMiniRefreshs = function(index) {
            //listDomArr[index] = document.querySelector('#listdata' + index);
            listDomArr[index] = '#chart' + index;
            var times=currTimes,type=String(parseInt(index)+1);
            var jparms={type:type,times:times,chart:listDomArr[index],index:index};
            requestform(jparms);

    };
     var navControl = document.querySelector('.nav-control'),CLASS_HIDDEN = 'minirefresh-hidden';
     bindEvent('.nav-control p', function(e) {
                var type = this.getAttribute('list-type');
                type = +type;
                if (type !== currIndex) {
                    navControl.querySelector('.active').classList.remove('active');
                    this.classList.add('active');
                    document.querySelector('#minirefresh' + currIndex).classList.add(CLASS_HIDDEN);
                    document.querySelector('#minirefresh' + type).classList.remove(CLASS_HIDDEN);
                    currIndex = type;
                    if (!miniRefreshArr[currIndex]) {
                        initMiniRefreshs(currIndex);
                    }
                }
            }, 'click');

            // 初始化
    initMiniRefreshs(0);

    //图标创建
        function drawCharts(x_data,y_data,info){
            var id=info.cahrtId,title=info.chartTitle,plot=info.chartPlot,index=info.index;
            var timesArr=new Array();
            var salesArr= new Array();
            for(var i=0;i<x_data.length;i++){
                timesArr.push(x_data[i]);
                if(index==4)
                    continue;
                else
                    salesArr.push(parseFloat(y_data[i]));
            }
            if(index==4)
                salesArr=y_data;
            var option={
                title:{text:title},
                tooltip:{},
                legend:{data:['浏览量']},
                xAxis:{data:timesArr},
                yAxis:{},
                grid:{x:45,y:50,x2:25,y2:25},
                series:[{
                    name:'浏览量',
                    type:plot,
                    data:salesArr
                }]
            };

            var resizeOpt={
                width:windowWidth
            }
            if(index==0){
                chartview0.setOption(option);
                chartview0.resize(resizeOpt);
            }else if(index==1){
                if(timesArr.length>10){
                    //取前五位来源显示
                    timesArr=timesArr.slice(0,6);
                    salesArr=salesArr.slice(0,6);
                }
                option={
                title:{text:title},
                tooltip:{},
                legend:{data:['浏览量']},
                xAxis:{data:timesArr},
                yAxis:{},
                grid:{x:45,y:50,x2:25,y2:25},
                series:[{
                    name:'浏览量',
                    type:plot,
                    data:salesArr
                    }]
                };
                chartview1.setOption(option);
                chartview1.resize(resizeOpt);
            }else if(index==2){
                var dataArr=new Array();
                //取前十位
                if(timesArr.length<10){
                    for(var i=0;i<timesArr.length;i++){
                    var dobj={value:salesArr[i],name:timesArr[i]};
                    dataArr.push(dobj);
                    }
                }else{
                     for(var i=0;i<10;i++){
                    var dobj={value:salesArr[i],name:timesArr[i]};
                    dataArr.push(dobj);
                    }
                }

                option={
                title:{
                    text:title,
                    x:'center'
                },
                tooltip:{
                    trigger:'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend:{
                   data: ['国家']
                },
                 series : [
                    {
                        name: '流量分布',
                        type: 'pie',
                        radius : '55%',
                        center: ['50%', '60%'],
                        data:dataArr,
                        itemStyle: {
                            emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                                      }
                                    }
                     }
                  ]
             }
                chartview2.setOption(option);
                chartview2.resize(resizeOpt);
            }else if(index==3){
                option={
                title:{text:title},
                tooltip:{},
                legend:{data:['订单金额/$']},
                xAxis:{
                    type: 'category',
                    boundaryGap: false,
                    data:timesArr
                },
                yAxis:{type:'value'},
                grid:{x:45,y:50,x2:25,y2:25},
                series:[{
                    name:'订单金额/$',
                    type:plot,
                    data:salesArr
                    }]
                };
                chartview3.setOption(option);
                chartview3.resize(resizeOpt);
            }else{
                option={
                title:{},
                tooltip:{},
                legend:{data:['Brazil','Russia','United States','China','Germany','Austria']},
                xAxis:{data:timesArr},
                yAxis:{},
                grid:{x:45,y:50,x2:25,y2:25},
                series:[
                    {
                    name:'Brazil',
                    type:plot,
                    data:salesArr[0]
                    },
                    {
                    name:'Russia',
                    type:plot,
                    data:salesArr[1]
                    },
                    {
                    name:'United States',
                    type:plot,
                    data:salesArr[2]
                    },
                    {
                    name:'China',
                    type:plot,
                    data:salesArr[3]
                    },
                    {
                    name:'Germany',
                    type:plot,
                    data:salesArr[4]
                    },
                    {
                    name:'Austria',
                    type:plot,
                    data:salesArr[5]
                    }]
                };
                chartview4.setOption(option);
                chartview4.resize(resizeOpt);
            }


        }
    });
